package cn.lblbc.stopwatch

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import cn.lblbc.stopwatch.databinding.ActivityLblBinding

/**
 * 厦门大学计算机专业 | 前华为工程师
 * 专注《零基础学编程系列》http://lblbc.cn/blog
 * 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
 * 公众号：蓝不蓝编程
 */
class LblActivity : AppCompatActivity() {
    private val interval = 50L
    private var startTime = 0L
    private var timeElapsed = 0L
    private var isStarted = false
    private var handler = Handler(Looper.getMainLooper())
    private lateinit var binding: ActivityLblBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_lbl)
        binding = ActivityLblBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.resetTv.setOnClickListener { resetTimer() }
        binding.startPauseTv.setOnClickListener { startPauseTimer() }
    }

    private fun startPauseTimer() {
        if (isStarted) {
            pauseTimer()
        } else {
            startTimer()
        }
        isStarted = !isStarted
    }

    private fun startTimer() {
        startTime = System.currentTimeMillis()
        handler.postDelayed({ changeText() }, interval)
        showPauseBtn()
    }

    private fun changeText() {
        val offset = System.currentTimeMillis() - startTime + timeElapsed
        binding.timeTv.text = TimeUtil.formatTime(offset)
        handler.postDelayed({ changeText() }, interval)
    }

    private fun pauseTimer() {
        handler.removeCallbacksAndMessages(null)
        timeElapsed += System.currentTimeMillis() - startTime
        showStartBtn()
    }

    private fun resetTimer() {
        handler.removeCallbacksAndMessages(null)
        timeElapsed = 0
        showStartBtn()
        binding.timeTv.text = getString(R.string.default_time)
    }

    private fun showStartBtn() {
        binding.startPauseTv.text = "开始"
    }

    private fun showPauseBtn() {
        binding.startPauseTv.text = "暂停"
    }
}